package com.itzg.vboxfarm.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Service;

import com.itzg.vboxfarm.domain.ConnectionStatus;
import com.itzg.vboxfarm.domain.HostMachine;
import com.itzg.vboxfarm.service.bits.HostChangedEvent;
import com.itzg.vboxfarm.service.bits.HostChangedEvent.Type;

@Service
public class HostConnectionResolver implements ApplicationListener<HostChangedEvent>, SmartLifecycle {
	
	private static Logger logger = LoggerFactory.getLogger(HostConnectionResolver.class);
	
	@Autowired
	HostConfigService hostConfigService;
	
	@Autowired
	HostConnectionResolverInstance hostConnectionResolverInstance;

	private boolean running;

	public void resolve(HostMachine host) {
		logger.debug("Kicking off resolution of {}", host);
		hostConnectionResolverInstance.resolve(host);
	}
	
	@Override
	public void onApplicationEvent(HostChangedEvent evt) {
		if (evt.getType() == Type.ADDED) {
			resolve(evt.getHostMachine());
		}
	}

	@Override
	public boolean isRunning() {
		return running;
	}

	@Override
	public void start() {
		logger.debug("Looking for hosts in unknown connection state");
		for (HostMachine hostMachine : hostConfigService.getAllHosts()) {
			if (hostMachine.getConnectionStatus() == ConnectionStatus.UNKNOWN) {
				resolve(hostMachine);
			}
		}
		running = true;
	}

	@Override
	public void stop() {
		running = false;
	}

	@Override
	public int getPhase() {
		return 500;
	}

	@Override
	public boolean isAutoStartup() {
		return true;
	}

	@Override
	public void stop(Runnable callback) {
		stop();
		callback.run();
	}
}
